package com.kangfawei.thread;

import java.util.concurrent.*;

/**
 * @author 康发伟
 * 通过实现Callable接口创建线程实现买票功能
 */
public class CallableSaleTicket implements Callable<Boolean> {
    private Integer count = 100;

    @Override
    public Boolean call() throws InterruptedException {
        while(count > 0){
            sale();
            Thread.sleep(100);
        }

        return true;
    }

    private synchronized void sale(){
        if(count > 0){
            System.out.println(Thread.currentThread().getName() + "卖出了第" + (100-count+1) + "张票！");
            count -- ;
        }
    }

    public static void main(String[] args) {
        CallableSaleTicket sale = new CallableSaleTicket();

        // 创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> future = service.submit(sale);
        Future<Boolean> future2 = service.submit(sale);
        Future<Boolean> future3 = service.submit(sale);

//        try {
//            // 获取结果
//            boolean flag1 = future.get();
//            boolean flag2 = future2.get();
//            boolean flag3 = future3.get();
//
//            // 结束服务
            service.shutdown();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
    }
}
